<template>
  <div id="app-container">
    <header class="app-header">
      <h1>AI 提示词优化器</h1>
      <button @click="openModelManagementModalHandler" class="manage-models-button">模型管理</button>
    </header>

    <PromptOptimizationArea
      :selectedModelId="selectedModelId"
      :enabledModels="enabledModels"
      :originalPrompt="originalPrompt"
      :isProcessing="isProcessing"
      :currentQuestions="currentQuestions"
      :userAnswers="userAnswers"
      :isReadyToOptimize="isReadyToOptimize"
      :readyToOptimizeMessage="readyToOptimizeMessage"
      :optimizedPrompt="optimizedPrompt"
      @update:selectedModelId="selectedModelId = $event"
      @update:originalPrompt="originalPrompt = $event"
      @update:userAnswer="updateUserAnswer"
      @submit-prompt="submitPrompt"
      @submit-answer="submitAnswer"
      @finalize-optimization="finalizeOptimization"
    />

    <StatusMessages :errorMessage="errorMessage" :successMessage="successMessage" />

    <OptimizedResultArea
      :optimizedPrompt="optimizedPrompt"
      @copy-to-clipboard="copyToClipboard"
    />

    <ModelManagementModal
      :show="showModelManagementModal"
      :models="models"
      :isProcessing="isProcessing"
      :modelTestResults="modelTestResults"
      @close="closeModelManagementModalHandler"
      @open-add-model="openAddModelFormHandler"
      @open-edit-model="openEditModelFormHandler"
      @toggle-enabled="toggleModelEnabled"
      @test-connection="testModelConnection"
      @delete-model="deleteModel"
    />

    <ModelFormModal
      :show="showModelFormModal"
      :isEditing="isEditingModel"
      :modelData="modelForm"
      :isSubmitting="isSubmittingModelForm"
      @close="closeModelFormModalHandler"
      @save="saveModel"
    />

  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import PromptOptimizationArea from './components/PromptOptimizationArea.vue';
import StatusMessages from './components/StatusMessages.vue';
import OptimizedResultArea from './components/OptimizedResultArea.vue';
import ModelManagementModal from './components/ModelManagementModal.vue';
import ModelFormModal from './components/ModelFormModal.vue';
import { API_V1_BASE_URL } from './config.js';

// --- 现有状态变量 ---
const originalPrompt = ref('');
const currentQuestions = ref([]); // Questions from AI
const userAnswers = ref({}); // User's answers to AI questions { questionId: answer }
const optimizedPrompt = ref('');
const conversationId = ref(null);
const isProcessing = ref(false); // General processing state
const errorMessage = ref('');
const successMessage = ref('');
const isReadyToOptimize = ref(false);
const readyToOptimizeMessage = ref('');

// --- 模型管理相关状态变量 ---
const models = ref([]); // Full list of models from backend
const selectedModelId = ref(null); // ID of the model selected in the main UI
const showModelManagementModal = ref(false); // Visibility for model management modal
const showModelFormModal = ref(false); // Visibility for add/edit model form modal
const modelForm = ref({ // Data for the add/edit model form
  id: null,
  display_name: '',
  api_base_url: '',
  model_name_internal: '',
  api_key: '',
  is_enabled: true,
});
const isEditingModel = ref(false); // True if editing an existing model, false if adding new
const modelTestResults = ref({}); // Stores results of model connection tests { modelId: { success, message, testing } }
const isSubmittingModelForm = ref(false); // True when model form (add/edit) is being submitted

// --- API URLs ---
const API_OPTIMIZER_URL = `${API_V1_BASE_URL}/optimizer`;
const API_MODELS_URL = `${API_V1_BASE_URL}/models`;


// --- 辅助函数 ---
const clearMessages = () => {
  errorMessage.value = '';
  successMessage.value = '';
};

// 清除优化流程状态 (保留模型选择)
const resetOptimizationState = () => {
  currentQuestions.value = [];
  userAnswers.value = {};
  optimizedPrompt.value = '';
  conversationId.value = null;
  clearMessages();
  isReadyToOptimize.value = false;
  readyToOptimizeMessage.value = '';
};

// --- Model Management Modal Handlers ---
const openModelManagementModalHandler = () => {
  fetchModels(); // Refresh models when opening
  showModelManagementModal.value = true;
};
const closeModelManagementModalHandler = () => {
  showModelManagementModal.value = false;
};

// --- Model Form Modal Handlers ---
const openAddModelFormHandler = () => {
  isEditingModel.value = false;
  modelForm.value = { // Reset form for new model
    id: null,
    display_name: '',
    api_base_url: '',
    model_name_internal: '',
    api_key: '',
    is_enabled: true,
  };
  // modelTestResults.value = {}; // Not strictly needed here as form is separate
  showModelFormModal.value = true;
};

const openEditModelFormHandler = (model_item) => {
  isEditingModel.value = true;
  modelForm.value = { ...model_item, api_key: '' }; // Pre-fill form, leave API key blank
  // modelTestResults.value = {};
  showModelFormModal.value = true;
};

const closeModelFormModalHandler = () => {
  showModelFormModal.value = false;
  // modelTestResults.value = {}; // Clear test results if any were associated with the form
};


// --- 模型管理 API 方法 ---
const fetchModels = async () => {
  clearMessages();
  try {
    const response = await fetch(API_MODELS_URL);
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({ detail: response.statusText }));
      throw new Error(`获取模型列表失败: ${errorData.detail || response.statusText}`);
    }
    models.value = await response.json();
    // Auto-select first enabled model if current selection is invalid or no model is selected
    if (!selectedModelId.value || !models.value.some(m => m.id === selectedModelId.value && m.is_enabled)) {
      const firstEnabledModel = models.value.find(m => m.is_enabled);
      selectedModelId.value = firstEnabledModel ? firstEnabledModel.id : null;
    }
  } catch (error) {
    errorMessage.value = error.message;
    console.error('Error fetching models:', error);
  }
};

const saveModel = async (formData) => {
  clearMessages();
  // Basic validation (can be enhanced)
  if (!formData.display_name || !formData.model_name_internal || !formData.api_base_url) {
    errorMessage.value = '显示名称、模型名称和 API Base URL 不能为空。';
    return;
  }
  if (isEditingModel.value && !formData.id) {
     errorMessage.value = '编辑模型时发生错误：缺少模型ID。';
     return;
  }
  if (!isEditingModel.value && !formData.api_key) {
    errorMessage.value = '新增模型时，API密钥不能为空。';
    return;
  }

  isSubmittingModelForm.value = true;
  const url = isEditingModel.value ? `${API_MODELS_URL}/${formData.id}` : API_MODELS_URL;
  const method = isEditingModel.value ? 'PUT' : 'POST';

  const payload = { ...formData };
  if (isEditingModel.value && !payload.api_key) { // If API key is empty during edit, don't send it
    delete payload.api_key;
  }
  if (!isEditingModel.value) { // ID should not be in POST body for new models
    delete payload.id;
  }

  try {
    const response = await fetch(url, {
      method: method,
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });
    const responseData = await response.json();
    if (!response.ok) {
      throw new Error(responseData.detail || `保存模型失败: ${response.statusText}`);
    }
    successMessage.value = `模型 "${responseData.display_name}" 已成功${isEditingModel.value ? '更新' : '添加'}。`;
    fetchModels(); // Refresh model list
    closeModelFormModalHandler(); // Close the form modal
  } catch (error) {
    errorMessage.value = error.message; // Show error in the form modal or main page
    console.error('Error saving model:', error);
  } finally {
    isSubmittingModelForm.value = false;
  }
};

const deleteModel = async (modelId, modelName) => {
  clearMessages();
  if (!confirm(`确定要删除模型 "${modelName}" 吗？此操作不可撤销。`)) {
    return;
  }
  try {
    const response = await fetch(`${API_MODELS_URL}/${modelId}`, { method: 'DELETE' });
    if (!response.ok && response.status !== 204) { // 204 is success for DELETE
      let errorDetail = `删除模型失败: ${response.statusText}`;
      if (response.headers.get('content-type')?.includes('application/json')) {
          const errorData = await response.json().catch(() => null);
          if (errorData && errorData.detail) {
              errorDetail = errorData.detail;
          }
      }
      throw new Error(errorDetail);
    }
    successMessage.value = `模型 "${modelName}" 已成功删除。`;
    fetchModels(); // Refresh list
    if (selectedModelId.value === modelId) { // If deleted model was selected
        selectedModelId.value = null;
        const firstEnabled = models.value.find(m => m.is_enabled);
        if (firstEnabled) selectedModelId.value = firstEnabled.id;
    }
  } catch (error) {
    errorMessage.value = error.message;
    console.error('Error deleting model:', error);
  }
};

const testModelConnection = async (modelId) => {
  clearMessages();
  modelTestResults.value[modelId] = { testing: true, success: false, message: '测试中...' };
  try {
    const response = await fetch(`${API_MODELS_URL}/${modelId}/test`, { method: 'POST' });
    const data = await response.json();
    modelTestResults.value[modelId] = { testing: false, success: data.success, message: data.message };
  } catch (error) {
    modelTestResults.value[modelId] = { testing: false, success: false, message: `测试请求失败: ${error.message}` };
    console.error('Error testing model connection:', error);
  }
};

const toggleModelEnabled = async (model_item) => {
  clearMessages();
  // For PUT, we need to send all required fields of ModelConfigUpdate, or ensure backend handles partials.
  // Backend's ModelConfigUpdate allows optional fields. So sending just is_enabled is fine.
  const payload = { is_enabled: !model_item.is_enabled };

  try {
    const response = await fetch(`${API_MODELS_URL}/${model_item.id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });
    const responseData = await response.json();
     if (!response.ok) {
      throw new Error(responseData.detail || `更新模型状态失败: ${response.statusText}`);
    }
    successMessage.value = `模型 "${responseData.display_name}" 状态已更新。`;
    // Update local model state immediately for better UX, then fetch to confirm
    const localModel = models.value.find(m => m.id === model_item.id);
    if (localModel) localModel.is_enabled = !localModel.is_enabled;
    fetchModels(); // Re-fetch to ensure consistency and update selectedModelId if needed
  } catch (error) {
    errorMessage.value = error.message;
    console.error('Error toggling model enabled state:', error);
    fetchModels(); // Re-fetch on error to revert optimistic update
  }
};

// --- 现有 API 交互方法 (修改后) ---
const handleApiResponse = (data) => {
  isProcessing.value = false;

  if (data.type === 'questions') {
    currentQuestions.value = data.content;
    userAnswers.value = currentQuestions.value.reduce((acc, q) => {
      acc[q.id] = '';
      return acc;
    }, {});
    conversationId.value = data.conversation_id;
    isReadyToOptimize.value = false;
    readyToOptimizeMessage.value = '';
  } else if (data.type === 'ready_to_optimize') {
    isReadyToOptimize.value = true;
    readyToOptimizeMessage.value = data.content;
    conversationId.value = data.conversation_id;
    currentQuestions.value = [];
    userAnswers.value = {};
  } else if (data.type === 'optimized_prompt') {
    optimizedPrompt.value = data.content;
    currentQuestions.value = [];
    userAnswers.value = {};
    isReadyToOptimize.value = false;
    readyToOptimizeMessage.value = '';
    successMessage.value = '提示词已成功优化！';
  } else if (data.type === 'error') {
    errorMessage.value = data.content || '发生未知错误。';
  } else {
    console.warn('Received unknown response type from optimizer:', data);
  }
};

// 提交原始提示词
const submitPrompt = async () => {
  if (!selectedModelId.value) {
    errorMessage.value = "请先选择一个模型。";
    return;
  }
  isProcessing.value = true;
  resetOptimizationState();

  try {
    const response = await fetch(`${API_OPTIMIZER_URL}/initiate`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        prompt: originalPrompt.value,
        selected_model_id: selectedModelId.value,
      }),
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.detail || `请求初始化失败: ${response.statusText}`);
    handleApiResponse(data);
  } catch (error) {
    isProcessing.value = false;
    errorMessage.value = '请求失败: ' + error.message;
    console.error('Error submitting prompt:', error);
  }
};

// Handler for updating user answers from PromptOptimizationArea component
const updateUserAnswer = ({ questionId, answer }) => {
  userAnswers.value[questionId] = answer;
};

// 提交用户回答
const submitAnswer = async () => {
  if (!conversationId.value) {
    errorMessage.value = "无效的会话，请重新开始。";
    return;
  }
  isProcessing.value = true;
  clearMessages();

  const formattedAnswer = currentQuestions.value.map(q => {
    const answer = userAnswers.value[q.id] || '';
    return `${q.question}\n我的回答: ${answer}`;
  }).join('\n\n');

  try {
    const response = await fetch(`${API_OPTIMIZER_URL}/refine`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        conversation_id: conversationId.value,
        answer: formattedAnswer, // Send the combined string
      }),
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.detail || `提交回答失败: ${response.statusText}`);
    // userAnswers.value = {}; // Clear answers after successful submission is handled by handleApiResponse or resetOptimizationState
    handleApiResponse(data);
  } catch (error) {
    isProcessing.value = false;
    errorMessage.value = '请求失败: ' + error.message;
    console.error('Error submitting answer:', error);
  }
};

// 生成最终优化提示词
const finalizeOptimization = async () => {
  if (!selectedModelId.value) {
    errorMessage.value = "请先选择一个模型。";
    return;
  }
  if (!conversationId.value) {
    errorMessage.value = "无效的会话，请重新开始。";
    return;
  }
  isProcessing.value = true;
  clearMessages();

  try {
    const response = await fetch(`${API_OPTIMIZER_URL}/finalize`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        conversation_id: conversationId.value,
        selected_model_id: selectedModelId.value,
      }),
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.detail || `生成优化提示词失败: ${response.statusText}`);
    handleApiResponse(data);
  } catch (error) {
    isProcessing.value = false;
    errorMessage.value = '请求失败: ' + error.message;
    console.error('Error finalizing optimization:', error);
  }
};

// 计算属性：获取启用的模型列表，用于下拉框
const enabledModels = computed(() => {
  return models.value.filter(model => model.is_enabled);
});

// 组件挂载时获取模型列表
onMounted(() => {
  fetchModels();
});

// 复制优化后的提示词到剪贴板
const copyToClipboard = async () => {
  clearMessages();

  if (!optimizedPrompt.value) {
    return;
  }

  try {
    if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
      await navigator.clipboard.writeText(optimizedPrompt.value);
      successMessage.value = '优化后的提示词已复制到剪贴板！';
      setTimeout(() => { successMessage.value = ''; }, 3000);
      return;
    } else {
      throw new Error('navigator.clipboard.writeText is not available.');
    }
  } catch (err) {
    console.warn('navigator.clipboard.writeText 失败或不可用:', err.message);
    const textarea = document.querySelector('.optimized-output');
    if (textarea) {
      textarea.select();
      textarea.focus();
      if (document.queryCommandSupported && document.queryCommandSupported('copy')) {
        try {
          const successful = document.execCommand('copy');
          if (successful) {
            successMessage.value = '提示词已通过备用方法复制到剪贴板。';
          } else {
            errorMessage.value = '自动复制失败。请选中提示词后手动复制 (Ctrl+C 或 Cmd+C)。';
          }
        } catch (execErr) {
          console.error('备用方法 document.execCommand("copy") 失败:', execErr);
          errorMessage.value = '自动复制时发生错误。请选中提示词后手动复制。';
        }
      } else {
        errorMessage.value = '您的浏览器不支持自动复制功能。请选中提示词后手动复制。';
      }
      setTimeout(() => {
        successMessage.value = '';
        errorMessage.value = '';
      }, 5000);
    } else {
      errorMessage.value = '无法找到文本区域以进行复制。';
      setTimeout(() => { errorMessage.value = ''; }, 3000);
    }
  }
};
</script>

<style scoped>
#app-container {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  max-width: 960px; /* Matches index.html #app */
  margin: 0 auto; /* Handled by index.html #app */
  padding: 0; /* Handled by index.html #app */
  background-color: transparent; /* Let body/index.html handle background */
  border-radius: 0; /* Let index.html handle border-radius */
  box-shadow: none; /* Let index.html handle shadow */
  color: #333;
  display: flex;
  flex-direction: column;
  gap: 25px; /* Spacing between main sections */
}

.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee; /* Subtle separator */
  margin-bottom: 5px; /* Reduced margin as gap handles spacing */
}

h1 {
  color: #2c3e50; /* Keep original dark blue for heading */
  margin: 0;
  font-size: 2.2em;
  flex-grow: 1;
  text-align: left; /* Align title to left */
}

.manage-models-button {
  background-color: #007bff; /* Primary blue */
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 8px; /* Slightly more rounded */
  cursor: pointer;
  font-size: 1em;
  transition: background-color 0.3s ease, transform 0.2s ease;
  box-shadow: 0 2px 5px rgba(0, 123, 255, 0.2); /* Subtle shadow */
}
.manage-models-button:hover {
  background-color: #0056b3; /* Darker blue on hover */
  transform: translateY(-1px); /* Slight lift effect */
}
.manage-models-button:active {
  transform: translateY(0);
}

/* General button styles that might be shared or overridden by components */
button {
  background-color: #28a745; /* Success green */
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1em;
  transition: background-color 0.3s ease, transform 0.2s ease;
  margin-right: 15px; /* Increased margin */
  box-shadow: 0 2px 5px rgba(40, 167, 69, 0.2);
}
button:last-child {
  margin-right: 0;
}
button:hover:not(:disabled) {
  background-color: #218838; /* Darker green on hover */
  transform: translateY(-1px);
}
button:active {
  transform: translateY(0);
}
button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
  box-shadow: none;
}
</style>
